<template>
  <div class="activity-container">
    <div class="toolbar">
      <el-button-group>
        <el-button
          v-for="item in activityTypes"
          :key="item.value"
          :type="activeType === item.value ? 'primary' : ''"
          @click="activeType = item.value">
          {{ item.label }}
        </el-button>
      </el-button-group>
      <div style="flex: 1;"></div>
      <el-button type="primary" icon="el-icon-plus" @click="handleCreate">新建</el-button>
    </div>

    <el-table :data="filteredActivities" style="width: 100%">
      <el-table-column prop="title" label="名称"></el-table-column>
      <el-table-column prop="type" label="类型" width="100">
        <template slot-scope="scope">
          <el-tag :type="scope.row.type | activityTypeFilter">
            {{ scope.row.type | activityTypeNameFilter }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="200">
        <template slot-scope="scope">
          <el-tag :type="getActivityStatus(scope.row) | statusTagTypeFilter">
            {{ getActivityStatus(scope.row) | activityStatusFilter }}
          </el-tag>
          <div v-if="scope.row.status === 0 && isExamStarted(scope.row)"
               style="color: #F56C6C; font-size: 12px; margin-top: 5px">
            考试已开始，请重新编辑
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="startTime" label="开始时间" width="180">
        <template slot-scope="scope">
          {{ scope.row.startTime | formatDateTime }}
        </template>
      </el-table-column>
      <el-table-column prop="endTime" label="结束时间" width="180">
        <template slot-scope="scope">
          {{ scope.row.endTime | formatDateTime }}
        </template>
      </el-table-column>
      <el-table-column prop="joinCount" label="参与人数" width="100"></el-table-column>
      <el-table-column label="操作" width="400">
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="handleEdit(scope.row)"
            :disabled="scope.row.status !== 0">
            编辑
          </el-button>

          <el-button-group v-if="scope.row.type !== 3" style="margin-left: 10px">
            <!-- 总是显示发布按钮，但对已开始考试禁用 -->
            <el-button
              size="mini"
              type="success"
              @click="handlePublish(scope.row)"
              :disabled="scope.row.status !== 0"
              v-if="scope.row.status === 0">
              发布
            </el-button>

            <!-- 撤回按钮 -->
            <el-button
              size="mini"
              type="warning"
              @click="handleRevoke(scope.row)"
              v-if="scope.row.status === 1 && !isExamStarted(scope.row)">
              撤回
            </el-button>
          </el-button-group>

          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)"
            :disabled="scope.row.status !== 0">
            删除
          </el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleViewParticipants(scope.row)">
            参加人员
          </el-button>
          <el-button
            type="text"
            @click="handlePreviewPaper({paperId: scope.row.paperId})"
          >
            预览试卷
          </el-button>

        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件添加 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pagination.pageNum"
      :page-sizes="[10, 20, 30, 50]"
      :page-size="pagination.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pagination.total"
      class="pagination-container">
    </el-pagination>

    <!-- 创建/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="80%"
      :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="活动类型" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio :label="1">考试</el-radio>
            <el-radio :label="2">测评</el-radio>
            <el-radio :label="3">作业</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="活动标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入活动标题"></el-input>
        </el-form-item>

        <el-form-item label="关联试卷" prop="paperId">
          <el-select
            v-model="form.paperId"
            filterable
            remote
            reserve-keyword
            placeholder="请搜索并选择试卷"
            :remote-method="searchPapers"
            :loading="paperLoading"
            @change="handlePaperChange"
            @visible-change="handlePaperSelectVisible"
            v-el-select-loadmore="loadMorePapers">
            <el-option
              v-for="item in paperOptions"
              :key="item.id"
              :label="`${item.title} (${item.code}) - ${item.totalScore}分`"
              :value="item.id">
              <span style="float: left">{{ item.title }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">
                {{ item.code }} | {{ item.totalScore }}分 | {{ item.questionCount }}题
              </span>
            </el-option>
            <div v-if="paperPagination.loading" class="loading-more">
              <i class="el-icon-loading"></i> 加载中...
            </div>
            <div v-if="paperPagination.noMore && paperOptions.length > 0" class="no-more">
              没有更多数据了
            </div>
          </el-select>
          <el-button
            type="text"
            @click="handlePreviewPaper({paperId: form.paperId})"
            :disabled="!form.paperId">
            预览试卷
          </el-button>
        </el-form-item>

        <el-form-item label="时间设置" required>
          <el-col :span="11">
            <el-form-item prop="startTime">
              <el-date-picker
                v-model="form.startTime"
                type="datetime"
                placeholder="选择开始时间"
                style="width: 100%"
                :disabled="form.type === 3">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="2" style="text-align: center">-</el-col>
          <el-col :span="11">
            <el-form-item prop="endTime">
              <el-date-picker
                v-model="form.endTime"
                type="datetime"
                placeholder="选择结束时间"
                style="width: 100%"
                :disabled="form.type === 3">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-form-item>

        <el-form-item label="身份验证" prop="needIdentity" v-if="form.type === 1">
          <el-switch v-model="form.needIdentity"></el-switch>
          <span class="tip-text">（考试需要验证身份，测评和作业不需要）</span>
        </el-form-item>

        <el-form-item label="时间限制(分钟)" prop="timeLimit" v-if="form.type !== 3">
          <el-input-number
            v-model="form.timeLimit"
            :min="1"
            :max="600"
            controls-position="right">
          </el-input-number>
        </el-form-item>

        <el-form-item label="参与分组" prop="subgroupIds">
          <el-tree
            ref="groupTree"
            :data="groupTreeData"
            show-checkbox
            node-key="id"
            :props="treeProps"
            :default-expand-all="true"
            @check-change="handleCheckChange">
          </el-tree>
          <div class="tip-text">（不选择任何分组则默认所有考生参加）</div>
        </el-form-item>

        <el-form-item label="排除成员" prop="excludedUserIds">
          <el-select
            v-model="form.excludedUserIds"
            multiple
            filterable
            remote
            reserve-keyword
            placeholder="请输入成员名称或ID搜索"
            :remote-method="searchMembers"
            :loading="memberLoading">
            <el-option
              v-for="item in memberOptions"
              :key="item.userId"
              :label="`${item.userName} (ID: ${item.userId})`"
              :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="高级配置" prop="configJson">
          <el-collapse>
            <el-collapse-item title="考试配置" name="1">
              <el-form-item label="允许切屏次数" prop="configJson.allowSwitchCount">
                <el-input-number
                  v-model="form.configJson.allowSwitchCount"
                  :min="0"
                  :max="10"
                  controls-position="right">
                </el-input-number>
              </el-form-item>
              <el-form-item label="强制全屏" prop="configJson.forceFullScreen">
                <el-switch v-model="form.configJson.forceFullScreen"></el-switch>
              </el-form-item>
              <el-form-item label="防作弊模式" prop="configJson.antiCheating">
                <el-switch v-model="form.configJson.antiCheating"></el-switch>
              </el-form-item>
            </el-collapse-item>
          </el-collapse>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitLoading">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 试卷预览对话框 -->
    <el-dialog
      title="试卷预览"
      :visible.sync="previewPaperVisible"
      width="80%"
      top="5vh">
      <paper-preview
        v-if="previewPaperVisible"
        :paper="previewPaperData"
        @edit-question="handleEditQuestion">
      </paper-preview>
      <div slot="footer" class="dialog-footer">
        <el-button @click="previewPaperVisible = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import dayjs from 'dayjs';
import timezone from 'dayjs/plugin/timezone';
import utc from 'dayjs/plugin/utc';

import PaperPreview from '@/views/paper2/manual/PaperPreview.vue'
import {getDicts} from '@/api/system/dict/data'
import {getExamSubgroups} from "@/api/exam/subGroup";
import {
  getPapers,
  getExamGroupMembers,
  getExamActivities,
  addExam,
  updateExam,
  deleteExam,
  getExamDetail,
  previewPaper,
  updateStatus
} from '@/api/exam/examActivity'


export default {
  components: {
    PaperPreview
  },
  props: {
    groupId: {
      type: [Number,String],
      required: true
    },
    initialActivities: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      // 分页配置
      pagination: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
        loading: false
      },
      paperPagination: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
        loading: false,
        noMore: false
      },

      activeType: null,
      activityTypes: [
        {value: null, label: '全部'},
        {value: 1, label: '考试'},
        {value: 2, label: '测评'},
        {value: 3, label: '作业'}
      ],
      activities: [],
      dialogVisible: false,
      dialogTitle: '新建活动',
      form: {
        id: null,
        examGroupId: this.groupId,
        type: 1,
        title: '',
        paperId: null,
        paperTitle: '',
        startTime: null,
        endTime: null,
        needIdentity: true,
        timeLimit: 120,
        subgroupIds: [],
        excludedUserIds: [],
        configJson: {
          allowSwitchCount: 3,
          forceFullScreen: true,
          antiCheating: true
        }
      },
      rules: {
        type: [{required: true, message: '请选择活动类型', trigger: 'change'}],
        title: [{required: true, message: '请输入活动标题', trigger: 'blur'}],
        paperId: [{required: true, message: '请选择关联试卷', trigger: 'change'}],
        startTime: [
          {
            required: true,
            validator: (rule, value, callback) => {
              const now = new Date();
              const selectedTime = value ? new Date(value) : null;

              if (this.form.type !== 3 && !value) {
                callback(new Error('请选择开始时间'));
              } else if (this.form.type !== 3 && selectedTime < now) {
                callback(new Error('开始时间不能早于当前时间'));
              } else if (this.form.type !== 3 && this.form.endTime && selectedTime >= new Date(this.form.endTime)) {
                callback(new Error('开始时间必须早于结束时间'));
              } else {
                callback();
              }
            },
            trigger: 'change'
          }
        ],
        endTime: [
          {
            required: true,
            validator: (rule, value, callback) => {
              const now = new Date();
              const selectedTime = value ? new Date(value) : null;
              const startTime = this.form.startTime ? new Date(this.form.startTime) : null;

              if (this.form.type !== 3 && !value) {
                callback(new Error('请选择结束时间'));
              } else if (this.form.type !== 3 && selectedTime < now) {
                callback(new Error('结束时间不能早于当前时间'));
              } else if (this.form.type !== 3 && startTime && selectedTime <= startTime) {
                callback(new Error('结束时间必须晚于开始时间'));
              } else {
                callback();
              }
            },
            trigger: 'change'
          }
        ],
        timeLimit: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (this.form.type !== 3 && !value) {
                callback(new Error('请输入时间限制'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ]
      },
      paperOptions: [],
      paperLoading: false,
      groupTreeData: [],
      treeProps: {
        label: 'name',
        children: 'children'
      },
      memberOptions: [],
      memberLoading: false,
      submitLoading: false,
      previewPaperVisible: false,
      previewPaperData: {},
      dicts: {
        exam_status: []
      }
    }
  },
  computed: {
    filteredActivities() {
      if (this.activeType === null) return this.activities
      return this.activities.filter(item => item.type === this.activeType)
    }
  },
  watch: {
    // initialActivities: {
    //   immediate: true,
    //   handler(val) {
    //     this.activities = JSON.parse(JSON.stringify(val))
    //   }
    // },
    activeType(newVal) {
      this.loadActivities()
    },
    'form.type'(val) {
      if (val === 3) { // 作业不需要时间限制和身份验证
        this.form.needIdentity = false
        this.form.timeLimit = null
        this.form.startTime = null
        this.form.endTime = null
      } else {
        this.form.needIdentity = val === 1
        this.form.timeLimit = this.form.timeLimit || 120
      }
    }
  },
  created() {
    this.loadDicts()
    this.loadGroupTree()
    this.loadActivities()
  },
  methods: {
    // 在 methods 中添加
    getActivityStatus(activity) {
      const now = new Date();
      const startTime = activity.startTime ? new Date(activity.startTime) : null;
      const endTime = activity.endTime ? new Date(activity.endTime) : null;

      // 作业只有草稿和已发布状态
      if (activity.type === 3) {
        return activity.status;
      }

      // 未发布的考试始终为未发布状态
      if (activity.status === 0) {
        return 0;
      }

      // 已发布的考试根据时间判断状态
      if (startTime && endTime) {
        if (now < startTime) {
          return 1; // 已发布但未开始
        } else if (now >= startTime && now <= endTime) {
          return 2; // 进行中
        } else {
          return 3; // 已结束
        }
      }
      return activity.status; // 默认返回保存的状态
    },
    // 检查考试是否已经开始
    isExamStarted(activity) {
      if (activity.type === 3 || !activity.startTime) return false;
      const now = new Date();
      const startTime = new Date(activity.startTime);
      return startTime <= now;
    },
    // 发布活动
    async handlePublish(row) {
      try {
        // 先检查考试是否已经开始
        if (this.isExamStarted(row)) {
          this.$confirm(
            '该考试已经开始，不能发布。是否需要重新编辑考试时间？',
            '提示',
            {
              confirmButtonText: '去编辑',
              cancelButtonText: '取消',
              type: 'warning'
            }
          ).then(() => {
            this.handleEdit(row); // 跳转到编辑页面
          });
          return;
        }

        // 正常发布流程
        await this.$confirm(`确定要发布 ${row.title} 吗?发布后将不能修改`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });

        const res = await updateStatus([row.id], 1);
        if (res.code === 200) {
          this.$message.success('发布成功');
          this.loadActivities();
        } else {
          this.$message.error(res.msg || '发布失败');
        }
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error(error.message || '操作失败');
        }
      }
    },

    // 撤回活动
    async handleRevoke(row) {
      try {
        await this.$confirm(`确定要撤回 ${row.title} 吗?撤回后可重新编辑`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });

        const res = await updateStatus([row.id], 0);
        if (res.code === 200) {
          this.$message.success('撤回成功');
          this.loadActivities();
        } else {
          this.$message.error(res.msg || '撤回失败');
        }
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error(error.message || '撤回失败');
        }
      }
    },

    // 查看参考人员
    handleViewParticipants(row) {
      this.$router.push({
        path: '/exam/group/participants',
        name: 'ExamParticipants',
        params: {
          examId: row.id,
          groupId: this.groupId
        }
      })
    },
    handlePaperSelectVisible(visible) {
      if (visible && this.paperOptions.length === 0) {
        this.searchPapers('') // 加载初始数据
      }
    },
    // 加载活动列表
    async loadActivities() {
      this.pagination.loading = true
      try {
        const params = {
          groupId: this.groupId,
          type: this.activeType
        }

        const response = await getExamActivities(params, {
          pageNum: this.pagination.pageNum,
          pageSize: this.pagination.pageSize
        })

        this.activities = response.rows
        this.pagination.total = response.total
      } catch (error) {
        console.error('加载活动列表失败:', error)
        this.$message.error('加载活动列表失败')
      } finally {
        this.pagination.loading = false
      }
    },
    // 分页大小改变
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.loadActivities()
    },

    // 当前页改变
    handleCurrentChange(val) {
      this.pagination.pageNum = val
      this.loadActivities()
    },
    loadDicts() {
      getDicts('exam_status').then(response => {
        this.dicts.exam_status = response.data
      })
    },

    // 加载分组数据
    async loadGroupTree() {
      try {
        const res = await getExamSubgroups(this.groupId)
        this.groupTreeData = this.buildTree(res.rows)
      } catch (error) {
        this.$message.error('加载分组失败: ' + error.message)
      }
    },
    async searchPapers(query = '') {
      if (this.paperPagination.loading) return

      this.paperPagination.loading = true
      this.paperLoading = true

      try {
        // 搜索时重置分页
        if (query !== this.lastPaperQuery) {
          this.paperPagination.pageNum = 1
          this.paperOptions = []
          this.lastPaperQuery = query
        }

        const params = {
          pageNum: this.paperPagination.pageNum,
          pageSize: this.paperPagination.pageSize,
          searchKey: query
        }

        const response = await getPapers(params)
        this.paperPagination.total = response.total

        // 合并结果
        this.paperOptions = [...this.paperOptions, ...response.rows.map(item => ({
          id: item.id,
          title: item.title,
          code: item.code,
          totalScore: item.totalScore,
          questionCount: item.questionCount
        }))]

        // 判断是否还有更多数据
        this.paperPagination.noMore = response.rows.length < this.paperPagination.pageSize
      } finally {
        this.paperPagination.loading = false
        this.paperLoading = false
      }
    },
    handlePaperChange(val) {
      const paper = this.paperOptions.find(item => item.id === val)
      if (paper) {
        this.form.paperTitle = paper.title
      }
    },
    searchMembers(query) {
      if (query !== '') {
        this.memberLoading = true
        getExamGroupMembers(this.groupId, query)
          .then(response => {
            this.memberOptions = response.rows
            this.memberLoading = false
          }).catch(() => {
          this.memberLoading = false
        })
      } else {
        this.memberOptions = []
      }
    },
    loadMorePapers() {
      if (this.paperPagination.noMore || this.paperPagination.loading) return

      this.paperPagination.pageNum++
      this.searchPapers(this.lastPaperQuery)
    },
    handleCheckChange() {
      const checkedNodes = this.$refs.groupTree.getCheckedNodes()
      this.form.subgroupIds = checkedNodes.map(node => node.id)
    },
    handleCreate() {
      this.dialogTitle = '新建活动'
      this.resetForm()
      this.dialogVisible = true
      this.$nextTick(() => {
        this.searchPapers()
        this.searchMembers()
      })
    },
    handleEdit(row) {

      if (row.status !== 0) {
        this.$message.warning('只有草稿状态的活动可以编辑')
        return
      }
      this.dialogTitle = '编辑活动'
      this.resetForm()


      this.dialogTitle = '编辑活动'
      this.resetForm()

      getExamDetail(row.id).then(response => {
        const data = response.data
        this.form = {
          id: data.id,
          examGroupId: data.examGroupId,
          type: data.type,
          title: data.title,
          paperId: data.paper.id,
          paperTitle: data.paper.title, // 确保设置 paperTitle
          startTime: data.startTime ? new Date(new Date(data.startTime).getTime() - 14 * 60 * 60 * 1000) : null,
          endTime: data.endTime ? new Date(new Date(data.endTime).getTime() - 14 * 60 * 60 * 1000) : null,
          needIdentity: data.needIdentity,
          timeLimit: data.timeLimit,
          subgroupIds: data.subgroupIds || [],
          excludedUserIds: data.excludedUsers ? data.excludedUsers.map(user => user.userId) : [],
          configJson: data.configJson || {
            allowSwitchCount: 3,
            forceFullScreen: true,
            antiCheating: true
          }
        }

        // 如果考试已经开始，显示警告
        if (this.isExamStarted(data)) {
          this.$nextTick(() => {
            this.$message.warning('该考试已经开始，请调整时间后再发布');
          });
        }

        // 设置试卷选项 - 确保包含完整的试卷信息
        if (data.paper) {
          this.paperOptions = [{
            id: data.paper.id,
            title: data.paper.title,
            code: data.paper.code || '',
            totalScore: data.paper.totalScore,
            questionCount: data.paper.questionCount
          }]
        }

        // 设置选中的分组
        this.$nextTick(() => {
          if (this.form.subgroupIds.length > 0) {
            this.$refs.groupTree.setCheckedKeys(this.form.subgroupIds)
          }
        })

        // 设置排除的成员
        if (data.excludedUsers) {
          this.memberOptions = data.excludedUsers
        }

        console.log('=====================>form', this.form)
        console.log('=====================>data', data)

        this.dialogVisible = true
      })
    },
    async handleDelete(row) {
      if (row.status !== 0) {
        this.$message.warning('只有草稿状态的活动可以删除')
        return
      }
      try {
        await this.$confirm(`确定要删除 ${row.title} 吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        await deleteExam(row.id)
        this.$message.success('删除成功')
        this.loadActivities() // 刷新列表
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败: ' + (error.message || error))
        }
      }
    },
    handlePreviewPaper(row) {
      previewPaper(row.paperId).then(response => {
        this.previewPaperData = response.data
        this.previewPaperVisible = true
      })
    },
    handleEditQuestion(question) {
      // 跳转到题目编辑页面
      this.$router.push(`/question/edit/${question.questionId}`)
      this.previewPaperVisible = false
    },
    resetForm() {
      this.form = {
        id: null,
        examGroupId: this.groupId,
        type: 1,
        title: '',
        paperId: null,
        paperTitle: '',
        startTime: null,
        endTime: null,
        needIdentity: true,
        timeLimit: 120,
        subgroupIds: [],
        excludedUserIds: [],
        configJson: {
          allowSwitchCount: 3,
          forceFullScreen: true,
          antiCheating: true
        }
      }

      if (this.$refs.form) {
        this.$refs.form.resetFields()
      }

      if (this.$refs.groupTree) {
        this.$refs.groupTree.setCheckedKeys([])
      }

      this.paperOptions = []
      this.memberOptions = []
    },
    async submitForm() {
      try {
        const valid = await this.$refs.form.validate()
        if (!valid) return

        // 检查时间有效性
        const now = new Date();
        if (this.form.type !== 3) {
          if (this.form.startTime && new Date(this.form.startTime) < now) {
            this.$message.warning('开始时间不能早于当前时间');
            return;
          }
          if (this.form.endTime && new Date(this.form.endTime) < now) {
            this.$message.warning('结束时间不能早于当前时间');
            return;
          }
          if (this.form.startTime && this.form.endTime
            && new Date(this.form.startTime) >= new Date(this.form.endTime)) {
            this.$message.warning('结束时间必须晚于开始时间');
            return;
          }
        }


        this.submitLoading = true

        const formData = JSON.parse(JSON.stringify(this.form))


        // 只保留0或1的状态
        formData.status = formData.status === 1 ? 1 : 0


        // 转换时间格式
        if (formData.startTime) {
          formData.startTime = dayjs(formData.startTime).format('YYYY-MM-DD HH:mm:ss')
        }
        if (formData.endTime) {
          formData.endTime = dayjs(formData.endTime).format('YYYY-MM-DD HH:mm:ss')
        }

        const api = formData.id ? updateExam : addExam
        await api(formData)

        this.$message.success(this.dialogTitle + '成功')
        this.dialogVisible = false
        this.loadActivities() // 刷新列表
      } catch (error) {
        this.$message.error('操作失败: ' + (error.message || error))
      } finally {
        this.submitLoading = false
      }
    },
    buildTree(data) {
      const tree = []
      const map = {}

      data.forEach(item => {
        map[item.id] = {...item, children: []}
      })

      data.forEach(item => {
        if (item.parentId) {
          if (map[item.parentId]) {
            map[item.parentId].children.push(map[item.id])
          }
        } else {
          tree.push(map[item.id])
        }
      })

      return tree
    },
  },
  filters: {
    activityTypeFilter(type) {
      const map = {1: 'danger', 2: 'warning', 3: 'success'}
      return map[type] || ''
    },
    activityTypeNameFilter(type) {
      const map = {1: '考试', 2: '测评', 3: '作业'}
      return map[type] || ''
    },
    activityStatusFilter(status) {
      const map = {
        0: '未发布',
        1: '已发布',
        2: '进行中',
        3: '已结束'
      };
      return map[status] || '';
    },
    statusTagTypeFilter(status) {
      const map = {
        0: 'info',
        1: 'success',
        2: 'warning',
        3: 'danger'
      };
      return map[status] || '';
    },
    formatDateTime(date) {
      if (!date) return '--'
      return date ? new Date(date).toLocaleString() : '--'
    }
  }
}
</script>

<style scoped>
.toolbar {
  display: flex;
  margin-bottom: 20px;
}

.tip-text {
  color: #999;
  font-size: 12px;
  margin-left: 10px;
}

.el-select, .el-cascader {
  width: 100%;
}

.el-date-editor {
  width: 100%;
}

.loading-more, .no-more {
  padding: 8px 0;
  text-align: center;
  color: #999;
  font-size: 12px;
}

.loading-more i {
  margin-right: 5px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>
